package com.market.cash.ui.fragment

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.market.cash.R
import com.market.cash.configs.CashRootConfigs
import com.market.cash.databinding.CashStepContactBinding
import com.market.cash.http.ApiService.addCommonParams
import com.market.cash.pro.ProFragment
import com.market.cash.ui.activity.StepsActivity
import com.market.cash.ui.adapter.CashRootStepContactAdapter
import com.market.cash.utils.CashRootDensityUtil
import com.market.cash.utils.CashRootStringDeepCopy
import com.market.cash.utils.event.CashRootEventType
import com.market.cash.utils.log.CashRootLog
import org.json.JSONArray
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/22 10:38
 * @Annotation：认证流程 - 联系人
 */
class StepContactFragment(): ProFragment() {
    lateinit var binding: CashStepContactBinding
    private var contactAdapter: CashRootStepContactAdapter? = null

    private var stepsAct: StepsActivity? = null
    private var stepItem: JSONObject? = null
    private var stepTitle = ""
    constructor(act: StepsActivity,stepItem: JSONObject): this(){
        this.stepsAct = act
        this.stepItem = stepItem
    }

    override fun getCashRootRootView(inflater: LayoutInflater): View {
        binding = CashStepContactBinding.inflate(inflater)
        return binding.root
    }

    override fun initCashRootView() {
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#00000000"))
        if (stepItem != null){
            val stepTitle = stepItem!!.optString("showTitle")
            binding.textStepTitle.text = stepTitle
            binding.textStepDes.text = String.format(getString(R.string.step_commom_des),stepTitle)
        }
        initCashRootRecyclerViews()
    }

    override fun initCashRootListener() {
        //添加
        binding.btnAdd.setOnClickListener {
            val lastItem = JSONObject(CashRootStringDeepCopy(contactAdapter!!.lastItem.toString()).content)
            val dataArray = lastItem.optJSONArray("dataList")
            if (dataArray != null) {
                for (i in 0..<dataArray.length()){
                    dataArray.optJSONObject(i).put("selectItem",null)
                }
            }
            contactAdapter!!.addLastItem(lastItem)
            contactAdapter!!.notifyDataSetChangedWrapper()

            //最多添加50个联系人
            if (contactAdapter!!.itemCount >= 50){
                binding.btnAdd.isEnabled = false
                binding.btnAdd.setBackgroundResource(R.drawable.cash_circle_fill_dfe1e8)
            } else {
                binding.btnAdd.isEnabled = true
                binding.btnAdd.setBackgroundResource(R.drawable.cash_circle_fill_435cfa)
            }
        }

        //提交
        binding.btnNext.setOnClickListener {
            if (!isAllowContactSubmit() || stepItem == null){
                showErrorTipsDialog(getString(R.string.tips_submit_error), stepTitle)
                return@setOnClickListener
            }
            val params = JSONObject().addCommonParams().apply {
                put("path",stepItem!!.optString("apiUrl").replace("/",""))
            }
            //拼接上传数据格式
            val paramArray = JSONArray()
            for (i in 0..<contactAdapter!!.itemCount){
                val obj = JSONObject()
                val dataArray = contactAdapter!!.getItem(i).optJSONArray("dataList")
                for (j in 0..<dataArray!!.length()){
                    val item = dataArray.optJSONObject(j)
                    obj.put(item.optString("paramName"),item?.optJSONObject("selectItem")!!.optString("value"))
                }
                paramArray.put(obj)
            }
            params.put(stepItem!!.optString("contactParamName"),paramArray)

            stepsAct!!.onCashRootSubmitAction(params)
            addCashRootEventPoint(String.format(CashRootEventType.CLICK.CASHROOT_CLICK_STEP_XX_NEXT, stepTitle),"")
        }
    }

    override fun initCashRootData() {
        val dataList = arrayListOf<JSONObject>()
        if (stepItem != null){
            // TODO: 这里dataList需要深拷贝，否则列表会共用一个数据源
            val stringCopy = CashRootStringDeepCopy(stepItem!!.optString("dataList"))
            for (i in 0..<stepItem!!.optInt("itemCount")){
                val obj = JSONObject()
                val dataArray = JSONArray(stringCopy.content)
                for (j in 0..<dataArray.length()){
                    val dataObj = dataArray.optJSONObject(j)
                    dataObj.put("title",dataObj.optString("title"))
                    when(dataObj.optString("action")){
                        "CONTACT_GROUP_RELATION",
                        "SELECT",
                        -> {
                            dataObj.put("action", "SELECT")
                            var relationShips = stepItem!!.optJSONArray("relationShips")
                            if (CashRootConfigs.isSwahili()){
                                relationShips = stepItem!!.optJSONArray("relationShips_sw")
                            }
                            val valueArray = relationShips?.optJSONArray(i)
                            val values = JSONArray()
                            for (n in 0..<valueArray!!.length()) {
                                val value = JSONObject()
                                value.put("title", valueArray.optString(n))
                                if (CashRootConfigs.isSwahili()){
                                    value.put("title_sw", valueArray.optString(n))
                                }
                                value.put("value", valueArray.optString(n))
                                values.put(value)
                            }
                            dataObj.put("values", values)
                        }
                        "CONTACT_GROUP_PHONE" -> {//联系电话
                            dataObj.put("action","CONTACT_GROUP_PHONE")
                        }
                        else -> {
                            dataObj.put("action","INPUT")
                        }
                    }
                }
                obj.put("dataList",dataArray)
                dataList.add(obj)
            }
        }
        contactAdapter!!.data = dataList
    }

    /**
     * 初始化Views
     */
    private fun initCashRootRecyclerViews(){
        //        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.recyclerView.layoutManager = layoutManager
        val topDecoration = CashRootDensityUtil.dp2px(14f)
//        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(0,0,0,topDecoration))
        contactAdapter = CashRootStepContactAdapter(binding.root,binding.recyclerView)
        binding.recyclerView.adapter = contactAdapter!!
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        contactAdapter!!.setOnChildItemSelectMobileListener(object : CashRootStepContactAdapter.IChildItemSelectMobileListener{
            override fun onChildSelectMobileClick(parentPosition: Int, childModel: JSONObject) {

                stepsAct!!.pickContact?.startPickContact { contactName, contactMobile ->
                    CashRootLog.e(">>>>>>>>>>>>>>>>>>>>>$contactName>>>>>>>$contactMobile")

                    val obj = JSONObject()
                    obj.put("title",contactMobile)
                    obj.put("value",contactMobile)
                    childModel.put("selectItem", obj)
                    contactAdapter!!.notifyItemChanged(parentPosition)

                    addCashRootEventPoint(String.format(CashRootEventType.CLICK.CASHROOT_CLICK_STEP_XX_SELECT, childModel.optString("paramName")), "$contactName:$contactMobile")
                }
            }
        })
    }

    /**
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowContactSubmit(): Boolean{
        val dataList = arrayListOf<JSONObject>()
        for (i in 0..<contactAdapter!!.itemCount){
            val dataArray = contactAdapter!!.getItem(i).optJSONArray("dataList")
            for (j in 0..<dataArray!!.length()){
                val item = dataArray.optJSONObject(j)
                dataList.add(item)
            }
        }
        //是否允许提交
        var isAllow = true
        for (i in 0..<dataList.size){
            val item = dataList[i]
            //存在 isMust && isMust == ”NO“  非必填
            if (item.has("isMust") && item.optString("isMust") == "NO"){
                continue
            }
            //必填 && 没有内容 || 内容为空
            if (!item.has("selectItem") || item.optJSONObject("selectItem")?.optString("value")!!.isEmpty()){
                isAllow = false
                break
            }
        }
        return isAllow
    }

    override fun onStart() {
        super.onStart()
        if (stepItem != null){
            stepTitle = stepItem!!.optString("stepTitle")
        }
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_STEP_CONTACT_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_STEP_CONTACT_END)
    }
}